// 
//  Copyright © 2009 Jiří Zárevúcky <zarevucky.jiri@gmail.com>
// 
//  This program is free software: you can redistribute it and/or modify
//  it under the terms of the GNU Affero General Public License as
//  published by the Free Software Foundation, either version 3 of the
//  License, or (at your option) any later version.
// 
//  This program is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//  GNU Affero General Public License for more details.
// 
//  You should have received a copy of the GNU Affero General Public License
//  along with this program.  If not, see <http://www.gnu.org/licenses/>.
// 
// 


using System;
using System.Text;

namespace Galaxium.Protocol.Xmpp.Library.Utility
{
	public enum UuidVersion { TimeBased = 1, Posix, NameMD5, Random, NameSHA1 }
	public enum UuidVariant { NCS, RFC, Microsoft, Unknown }
	
	/// <summary>
	/// Implementation of RFC 4122
	/// TODO: implement other algoritms than just random
	/// </summary>
	public static class Uuid
	{
		public static readonly string Nil = "00000000-0000-0000-0000-000000000000";

		private static readonly Random rnd = new Random ();
		
		private static string ToTextForm (byte[] uuid)
		{
			StringBuilder sb = new StringBuilder ();
			for (int i = 0; i < uuid.Length; i++) {
				switch (i) {
				case 4:
				case 6:
				case 8:
				case 10: sb.Append ('-'); break;
				}
				sb.AppendFormat ("{0:x2}", uuid [i]);
			}
			return sb.ToString ();
		}
		
		public static string GenerateRandom ()
		{
			byte version = 4; // randomly generated uuid
			byte[] uuid = new byte[16];
			rnd.NextBytes (uuid);
			uuid [8] = (byte) ((uuid [8] | 0x80) & 0xBF);
			uuid [6] = (byte) ((uuid [6] & 0x0F) | (version << 4));
			return ToTextForm (uuid);
		}
	}
}
